<template>
  <div>
    <a-page-header
      style="border: 1px solid rgb(235, 237, 240)"
      :title="getTitle"
      :ghost="false"
      @back="() => $router.go(-1)"
    ></a-page-header>

    <page-header-wrapper>
      <a-card :border="false">
        <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
          <div class="g-title">活动设置</div>
          <a-form-model-item label="活动名称" prop="name">
            <a-input class="maxWidth" v-model="form.name" allowClear />
          </a-form-model-item>
          <a-divider />

          <div class="g-title">时间设置</div>
          <a-form-model-item label="活动时间" prop="queryTime">
            <a-range-picker
              class="maxWidth"
              style="width: 100%"
              format="YYYY-MM-DD HH:mm"
              valueFormat="YYYY-MM-DD HH:mm"
              :placeholder="['开始时间', '结束时间']"
              v-model="form.queryTime"
            />
          </a-form-model-item>
          <a-divider />

          <div class="g-title">返利数量</div>
          <a-form-model-item label="每人限购">
            <div class="flex maxWidth">
              <a-input-number style="width: 100%" v-model="form.buy_limit" clas="flexInp"></a-input-number>
              <div class="flexTxt">件</div>
            </div>
          </a-form-model-item>
          <a-divider />

          <div class="g-title">活动商品</div>
          <a-form-model-item label="选择商品" prop="goods_ext">
            <a-button type="primary" @click="openGoods"> 添加商品 </a-button>

            <div class="goodsBox">
              <a-table :scroll="{ x: 800 }" :columns="columns" :data-source="getGoodsList" :pagination="false">
                <span slot="goodsInfo" slot-scope="text">
                  <div class="goodsInfo">
                    <div class="img">
                      <a-avatar shape="square" :size="48" :src="text.cover_pic" />
                    </div>

                    <div class="txt">
                      <a-tooltip placement="topLeft" :title="text.name">
                        <div class="name">{{ text.name }}</div>
                      </a-tooltip>
                    </div>
                  </div>
                </span>
                <span slot="price" slot-scope="text, item, index">
                  <a-input-number
                    class="setNum"
                    @change="(e) => onChange(e, index)"
                    :precision="2"
                    :min="0"
                    :value="text.price"
                  ></a-input-number>
                </span>
                <span slot="attrPrice" slot-scope="text, item, index">
                  <div class="setNum" @click="setPrice(text, index)">设置活动价格</div>
                </span>
                <span slot="actions" slot-scope="text, item, index">
                  <a-button type="link" @click="handle('remove', text, index)">删除</a-button>
                </span>
              </a-table>
            </div>

            <el-pagination
              :page-size="size"
              :current-page="page"
              background
              layout="prev, pager, next"
              @current-change="(e) => (page = e)"
              :total="form.goods_ext.length"
              v-if="form.goods_ext.length"
            >
            </el-pagination>
          </a-form-model-item>
          <a-divider />


          <a-divider />
        </a-form-model>

        <a-form-model-item label="">
          <a-button type="primary" :disabled="disabled" @click="onSubmit"> 提交 </a-button>
        </a-form-model-item>
      </a-card>

      <toolsGoods :selectedList="form.goods_ext" @onOk="selectGoods" ref="toolsGoods"></toolsGoods>

      <a-modal width="700px" v-model="visible" title="选择规格" @ok="submitAttr">
        <a-table :columns="attrColumns" :data-source="item" :pagination="false">
          <span slot="attr" slot-scope="text">
            <div class="goodsInfo">
              <div class="img">
                <a-avatar shape="square" :size="48" :src="text.pic" />
              </div>

              <div class="txt">
                <a-tooltip placement="topLeft" :title="text.attr_list.map((el) => el.attr_name).join('-')">
                  <div class="name">{{ text.attr_list.map((el) => el.attr_name).join('-') }}</div>
                </a-tooltip>
              </div>
            </div>
          </span>

          <span slot="price" slot-scope="text">
            <a-input-number class="setNum" v-model="text.price" :precision="2" :min="0"></a-input-number>
          </span>

          <!-- <span slot="price" slot-scope="text, item, index"> 

          </span> -->
        </a-table>
      </a-modal>

      <toolsCoupon
        @callBack="callBack"
        ref="toolsCoupon"
        :couponList="couponList"
        :checkedList="form.coupon_ids"
      ></toolsCoupon>
    </page-header-wrapper>
  </div>
</template>

<script>
import { Save, Info, getCoupons } from '@/api/marketing/activityNew'
import toolsGoods from '@/components/tools/tools-goods'
import toolsCoupon from '@/components/tools/tools-coupon'

export default {
  components: {
    toolsCoupon,
    toolsGoods,
  },
  data() {
    return {
      selectedRowKeys: [],
      categoryInfo: [],
      labelCol: { span: 3 },
      wrapperCol: { span: 19 },
      disabled: false,
      form: {
        name: '',
        queryTime: [],
        goods_ext: [],
        coupon_ids: [],
        buy_limit: '',
      },
      rules: {
        name: [{ required: true, message: '活动名称不能为空', trigger: 'blur' }],
        queryTime: [{ required: true, message: '活动时间不能为空', trigger: 'change' }],
        goods_ext: [{ required: true, message: '活动商品不能为空', trigger: 'change' }],
        coupon_ids: [{ required: true, message: '优惠券不能为空', trigger: 'change' }],
      },

      couponList: [],
      visible: false,
      id: 0,

      columns: [
        {
          title: '商品ID',
          dataIndex: 'goods_id',
          width: 80,
        },
        {
          title: '商品名称',
          scopedSlots: { customRender: 'goodsInfo' },
        },

        {
          title: '售价',
          dataIndex: 'oldPrice',
          sorter: (a, b) => a.oldPrice - b.oldPrice,
          width: 100,
        },
        {
          title: '总库存',
          dataIndex: 'goods_num',
          sorter: (a, b) => a.goods_num - b.goods_num,
          width: 100,
        },
        {
          title: '活动价格',
          scopedSlots: { customRender: 'price' },
        },
        {
          title: '活动规格价',
          scopedSlots: { customRender: 'attrPrice' },
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'actions' },
          width: 100,
          fixed: 'right',
        },
      ],

      attrColumns: [
        {
          title: '规格',
          scopedSlots: { customRender: 'attr' },
        },
        {
          title: '原价',
          dataIndex: 'oldPrice',
          sorter: (a, b) => a.oldPrice - b.oldPrice,
          width: 100,
        },
        {
          title: '活动价格',
          scopedSlots: { customRender: 'price' },
        },
        // {
        //   title: '是否参与',
        //   scopedSlots: { customRender: 'actions' },
        //   width: 100,
        //   fixed: 'right',
        // },
      ],

      couponColumns: [
        {
          title: 'id',
          dataIndex: 'id',
          width: 80,
        },
        {
          title: '优惠券名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
          width: 200,
        },
        {
          title: '优惠金额',
          scopedSlots: { customRender: 'youhui' },
        },
        {
          title: '最低消费',
          dataIndex: 'min_price',
          sorter: (a, b) => a.min_price - b.min_price,
        },
        {
          title: '优惠方式',
          scopedSlots: { customRender: 'type' },
        },
        {
          title: '有效时间',
          scopedSlots: { customRender: 'created_at' },
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'actions' },
          width: 100,
          fixed: 'right',
        },
      ],

      page: 1,
      size: 30,

      index: 1,
      item: [
        {
          attr_list: [
            { attr_id: 383, attr_name: 'XS-S(155cm)' },
            { attr_id: 384, attr_name: '象牙白色 现货' },
          ],
          no: '',
          pic: '',
          share_commission_first: '',
          share_commission_second: '',
          share_commission_third: '',
          virtual_sales: 50,
          price: 0.01,
          oldPrice: 0.01,
        },
        {
          attr_list: [
            { attr_id: 383, attr_name: 'XS-S(155cm)' },
            { attr_id: 387, attr_name: '黑色 现货' },
          ],
          no: '',
          pic: '',
          share_commission_first: '',
          share_commission_second: '',
          share_commission_third: '',
          virtual_sales: 50,
          price: 0.01,
          oldPrice: 0.01,
        },
      ],
    }
  },

  async mounted() {
    let { id } = this.$route.query
    this.id = parseInt(id)

    const res = await getCoupons()
    if (!res.code) {
      this.couponList = res.data || []
    }

    this.init()
  },

  watch: {},

  computed: {
    getGoodsIndex() {
      return (index) => {
        let { page, size } = this,
          active = (page - 1) * size + index

        return active
      }
    },
    getGoodsList() {
      let { form, page, size } = this,
        { goods_ext } = form,
        index = (page - 1) * size

      return JSON.parse(JSON.stringify(goods_ext)).splice(index, size) || []
    },
    getTitle() {
      return this.id ? '编辑' : '添加' + '活动'
    },
  },

  methods: {
    submitAttr() {
      let { item, form, index } = this

      if (item.every((el) => !el.price && typeof el.price != 'number')) {
        this.$message.error('活动价格不能为空~')
        return
      }

      this.visible = false
      this.$set(form.goods_ext[index], 'attr', item)
    },
    handle(type, item, index) {
      let activeIndex = this.getGoodsIndex(index)
      switch (type) {
        case 'remove':
          this.form.goods_ext.splice(activeIndex, 1)
          break
      }
    },
    setPrice(item, index) {
      let activeIndex = this.getGoodsIndex(index)
      this.index = activeIndex
      this.item = item.attr
      this.visible = true
    },
    onChange(val, index) {
      this.form.goods_ext[this.getGoodsIndex(index)].price = val
    },

    mergeData() {},

    clearGoods(list = []) {
      return list.map((el) => {
        let { cover_pic, name, goods_num, id: goods_id, price, use_attr } = el,
          obj = {
            oldPrice: el.oldPrice ? el.oldPrice : price,
            price,
            cover_pic,
            goods_num,
            goods_id,
            use_attr,
            name,
          }

        // if (use_attr === '1') {
        if (!el.attr) {
          obj.attr = []
        } else {
          obj.attr = typeof el.attr === 'string' ? JSON.parse(el.attr) : el.attr
        }
        // }
        return obj
      })
    },

    selectGoods(list) {
      this.$nextTick(() => {
        this.form.goods_ext.push(...this.clearGoods(list))
      })
      // let newList = list.map((el) => {
      //   let { cover_pic, name, goods_num, id: goods_id, price, use_attr } = el,
      //     obj = {
      //       oldPrice: price,
      //       price,
      //       cover_pic,
      //       goods_num,
      //       goods_id,
      //       use_attr,
      //       name,
      //     }

      //   if (use_attr === '1') {
      //     obj.attr = el.attr
      //   }
      //   return obj
      // })
      // newList
    },

    openGoods() {
      this.$nextTick(() => {
        let el = this.$refs.toolsGoods
        el.visible = true
      })
    },

    async init() {
      const hide = this.$message.loading('加载中', 0)

      let res = await Info({ id: this.id })
      if (!res.code) {
        let { activity, activity_goods, goods_ext, activity_coupons: coupon_ids } = res.data,
          { start_time, end_time, name, id, buy_limit } = activity,
          newGoodsList = this.clearGoods(activity_goods)

        newGoodsList.forEach((el) => {
          let item = goods_ext.find((e) => e.goods_id === parseInt(el.goods_id))
          if (item) {
            el.price = item.price
            el.id = item.id
            let oldAttr = typeof item.attr === 'string' && item.attr ? JSON.parse(item.attr) : [],
              attr = el.attr

            if (Array.isArray(attr)) {
              attr.forEach((e) => {
                let attrId = e.attr_list.map((el) => el.attr_id).join(','),
                  cItem = oldAttr.find((el) => {
                    return el.attr_list.map((el) => el.attr_id).join(',') === attrId
                  })

                if (cItem) {
                  e.price = cItem.price
                }

                e.oldPrice = e.price
              })
            }
          }
        })

        this.form = {
          id,
          name,
          queryTime: [start_time, end_time],
          buy_limit,
          goods_ext: newGoodsList,
          coupon_ids,
        }
      }
      hide()
    },

    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.disabled = true
          const hide = this.$message.loading('加载中', 0)
          let form = JSON.parse(JSON.stringify(this.form)),
            [start_time, end_time] = form.queryTime

          form.start_time = start_time
          form.end_time = end_time

          form.goods_ext = form.goods_ext.map((el) => {
            if (el.attr) {
              el.attr = JSON.stringify(el.attr)
            } else {
              el.attr = ''
            }
            return el
          })

          form.goods_ids = form.goods_ext.map((el) => el.goods_id).join(',')
          form.coupon_ids = form.coupon_ids.map((el) => el.id).join(',')
          delete form.queryTime

          const res = await Save(form)
          hide()
          this.disabled = false
          if (res.code == 0) {
            this.$message.success('创建成功')
            this.visible = false
            this.$router.back()
            return
          }
          this.$message.error(res.msg)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },

    callBack(e) {
      this.form.coupon_ids = e
    },
  },
}
</script>

<style lang="less" scoped>
.g-title {
  padding-bottom: 20px;
  font-size: 16px;
  font-weight: bold;
  color: #000;
}

.maxWidth {
  max-width: 468px;
}

.flex {
  display: flex;

  .flexInp {
    flex: 1;
    overflow: hidden;
  }

  .flexTxt {
    background: #f7f7f7;
    width: 41px;
    height: 32px;
    text-align: center;
    border: 1px solid #d9d9d9;
    border-left: 0;
    border-radius: 0 2px 2px 0;
  }
}

.goodsBox {
  margin: 10px 0;
}

.goodsInfo {
  width: 100%;
  display: flex;
  align-items: center;

  .img {
    width: 48px;
    height: 48px;
  }

  .txt {
    padding-left: 24px;
    flex: 1;
    overflow: hidden;

    .name {
      width: 100%;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.65);
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }
}

.setNum {
  display: flex;
  padding: 0 12px;
  width: 110px;
  height: 32px;
  line-height: 32px;
  border: 1px solid rgba(0, 0, 0, 0.149);
  border-radius: 4px;
}
</style>
